package com.heima.wemedia.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service

public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)

    public ResponseResult upLoad(MultipartFile multipartFile) throws IOException {

        // 1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        // 2 上传到oss
        String fileId = null;
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            String originalFilename = multipartFile.getOriginalFilename();
            String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId = fileStorageService.store(prefix, filename + postfix, multipartFile.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}", e);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite + fileId);
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);


    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */

    @Override
    public ResponseResult materialList(WmMaterialDto dto) {
//        //参数校验
//        if (dto == null || dto.getIsCollection() == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }

        dto.checkParam();

        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();

        // 查询收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 当前用户素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());

        // 时间排序(倒序)
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, wrapper);

        // 图片处理
        List<WmMaterial> wmMaterialList = resultPage.getRecords();
        for (WmMaterial wmMaterial : wmMaterialList) {
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        }
        // 结果封装
        PageResponseResult pageResponseResult = new PageResponseResult(
                dto.getPage()
                , dto.getSize()
                , (int) resultPage.getTotal()
        );
        pageResponseResult.setData(wmMaterialList);

        return pageResponseResult;

    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @param isCollection
     * @return
     */

    @Override
    public ResponseResult collection(Integer id, Integer isCollection) {
        //参数校验
        if (id == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //修改状态
        this.update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId, id).set(WmMaterial::getIsCollection, isCollection));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 删除文件
     *
     * @param id
     * @return
     */


    @Override
    public ResponseResult delete(Integer id) {
        //校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询是否有关联的文章
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (wmNewsMaterials.size() > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "该文件有关联文章，不能删除");
        }
        //获取要删除的oss路径
        WmMaterial wmMaterial = this.getById(id);
        String url = wmMaterial.getUrl();
        //删除文件
        fileStorageService.delete(url);
        this.removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}


